const {
	config
} = require('../../common/config.js')
const ServerError = require('../../common/error')

const db = uniCloud.database();

async function bannerAdd() {
	let curtime = Date.now()
	let httpInfo = this.getHttpInfo()
	let {
		url,
		sort,
		path,
		desciption,
		status
	} = JSON.parse(httpInfo.body)
	let data = await db.collection("banner").add({
		url,
		sort,
		path,
		desciption,
		status,
		ctime: curtime
	})
	if (data.id) {
		return {
			errCode: 0,
			data: data,
			errMsg: "添加成功"
		}
	} else {
		throw new ServerError("添加失败", 3001)
	}
}
async function bannerDelete() {
	let httpInfo = this.getHttpInfo()
	let {
		_id
	} = JSON.parse(httpInfo.body)

	let ids = [
		"638e074df5cf3a959a513600",
		"638e07dde1a35c299de9774c",
		"638e0800819ce8af3e745aa0",
		"638e0808f5cf3a959a513a73"
	];
	ids.filter((id) => {
		if (id == _id) {
			throw ServerError("禁止Update默认数据", 5555)
		}
	})
	let {
		deleted
	} = await db.collection("banner").doc(_id).remove()
	if (deleted) {
		return {
			errCode: 0,
			data: {
				deleted
			},
			errMsg: "删除成功"
		}
	} else {
		throw new ServerError("没有可删除的数据", 3009)
	}

}
async function bannerUpdate() {
	let curtime = Date.now()
	let httpInfo = this.getHttpInfo()
	let upData = JSON.parse(httpInfo.body)
	let _id = upData._id
	delete upData._id
	let ids = [
		"638e074df5cf3a959a513600",
		"638e07dde1a35c299de9774c",
		"638e0800819ce8af3e745aa0",
		"638e0808f5cf3a959a513a73"
	];
	ids.filter((id) => {
		if (id == _id) {
			throw ServerError("禁止Update默认数据", 5555)
		}
	})
	let {
		affectedDocs,
		updated
	} = await db.collection('banner').doc(_id).update(upData);
	if (updated > 0) {
		return {
			errCode: 0,
			data: {
				updated
			},
			errMsg: "更新"
		}
	} else {
		throw new ServerError("未知原因更新失败", 3012)
	}

}

async function bannerList(page = 0, limit = 10) {
	page = parseInt(page)
	limit = parseInt(limit)
	let {
		affectedDocs,
		data
	} = await db.collection('banner').get();
	return {
		errCode: 0,
		data: data,
		errMsg: "轮播图列表"
	}
}

module.exports = {
	bannerAdd,
	bannerDelete,
	bannerUpdate,
	bannerList,
}
